/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { Button, Col, Form, message, Row, Select } from 'antd';
import StandardTable from '@/components/StandardTable';
import { changePostName } from '@/utils/changePostCompanyName';

const FormItem = Form.Item;
const { Option } = Select;

const brands = ['all', 'sto', 'zt', 'yt', 'yd', 'jt', 'ems'];

const DispatStatisticsDetail = props => {
  const { form, dispatch, loading, deliveryPayDetails = {}, onChangeMode, detailRecord } = props;
  const { id: detailId, operator_kb_code, start_time, end_time } = detailRecord || {};
  const { getFieldDecorator, validateFields } = form;
  const [selectRows, setSelectRows] = useState([]);
  const { pagination = {}, list = [] } = deliveryPayDetails;
  const fotmatFormValue = then => {
    validateFields((error, values) => {
      if (error) return;
      const { brand } = values;
      then({
        brand: brand === 'all' ? '' : brand,
      });
    });
  };

  const onSubmit = pageOptions => {
    const { current } = pageOptions || {};
    fotmatFormValue(values => {
      dispatch({
        type: 'dispatStatistics/getDeliveryPayDetails',
        payload: {
          courier_no: operator_kb_code,
          operator_kb_code,
          start_time,
          end_time,
          ...values,
          page: current || 1,
        },
      });
    });
  };
  form.reload = () => onSubmit(deliveryPayDetails.pagination || {});

  const onGrantDispat = datalist => {
    const paramsList = Array.isArray(datalist) ? datalist : selectRows;
    const formatList = paramsList.filter(item => item.status !== '已发放').map(item => item.id);
    dispatch({
      type: 'dispatStatistics/manualDistributionFeeDetails',
      payload: { ids: formatList.toString(), courier_no: operator_kb_code },
    }).then(() => {
      message.success('发放成功');
      setSelectRows([]);
      form.reload();
    });
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      align: 'center',
    },
    {
      title: '业务员',
      dataIndex: 'courier_name',
      key: 'courier_name',
      align: 'center',
      render: (text, record) => `${record.courier_name} ${record.courier_phone}`,
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      align: 'center',
    },
    {
      title: '派件量',
      dataIndex: 'count',
      align: 'center',
    },
    {
      title: '派费',
      dataIndex: 'totalPrice',
      align: 'center',
    },
    {
      title: '是否发放',
      dataIndex: 'status',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <>
          {record.status !== '已发放' ? (
            <a onClick={onGrantDispat.bind(null, [record])} style={{ paddingLeft: 10 }}>
              发放
            </a>
          ) : (
            <span> -- </span>
          )}
        </>
      ),
    },
  ];

  useEffect(
    () => {
      if (detailId) {
        form.reload();
      }
    },
    [detailId],
  );

  const onExport = () => {
    const params = {
      courier_no: operator_kb_code,
      start_time,
      end_time,
      page: pagination.current || 1,
      is_export: '1',
    };
    fotmatFormValue(valuse => {
      params.brand = valuse.brand || '';
    });
    dispatch({
      type: 'dispatStatistics/getDeliveryPayDetails',
      payload: params,
    });
  };

  return (
    <>
      <Row type="flex" justify="space-between">
        <Col>
          <Form layout="inline" style={{ marginBottom: 24 }}>
            <FormItem label="快递品牌">
              {getFieldDecorator('brand', {
                initialValue: 'all',
              })(
                <Select style={{ width: 180 }}>
                  {brands.map(item => (
                    <Option key={item}>{changePostName(item, 'brand')}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" onClick={onSubmit}>
                查询
              </Button>
            </FormItem>
            <FormItem>
              <Button
                type="primary"
                icon="download"
                disabled={list.length === 0}
                onClick={onExport}
              >
                导出
              </Button>
            </FormItem>
          </Form>
        </Col>
        <Col>
          <Button type="primary" onClick={onChangeMode}>
            返回
          </Button>
        </Col>
      </Row>
      <StandardTable
        selectedRows={selectRows}
        onSelectRow={setSelectRows}
        rowKey="id"
        loading={loading}
        data={deliveryPayDetails}
        columns={columns}
        scroll={{ x: 800 }}
        onChange={onSubmit}
      />
      <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
        <Col>
          <Button
            onClick={onGrantDispat}
            disabled={!(selectRows.length && selectRows.some(item => item.status !== '已发放'))}
            type="primary"
          >
            批量发放
          </Button>
        </Col>
      </Row>
    </>
  );
};

export default connect(({ loading, dispatStatistics }) => ({
  loading: loading.effects['dispatStatistics/getDeliveryPayDetails'],
  dispatStatistics,
  deliveryPayDetails: dispatStatistics.deliveryPayDetails || {},
}))(React.memo(Form.create()(DispatStatisticsDetail)));
